package com.zhilingshenghuo.app.zhly.utils

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.view.View
import android.widget.ImageView
import androidx.annotation.RequiresApi
import com.zhilingshenghuo.app.zhly.R
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import org.jetbrains.anko.dip

/**
 * 加载圆角图片
 *
 * @param url            加载图片的url
 * @param roundedCorners 设置圆角, 如果该参数不加则会为圆形
 */
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
@SuppressLint("CheckResult")
fun ImageView.loadCircularImage(url: Any?, roundedCorners: Int, context: Context) {
    if (url == null || (url is CharSequence && url.isEmpty()) || url is Int && url == View.NO_ID) {
        setImageDrawable(context.getDrawable(R.drawable.icon_csc))
        return
    }

    val requestOptions = RequestOptions()
    if (roundedCorners == 0) {
        requestOptions.circleCrop()
    } else {
        requestOptions.transforms(CenterCrop(), RoundedCorners(context.dip(roundedCorners)))
    }
    requestOptions.placeholder(context.getDrawable(R.drawable.icon_csc))

    Glide.with(context).load(url).apply(requestOptions).into(this)
}

/**
 * 加载图片
 */
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
@SuppressLint("CheckResult")
fun ImageView.loadImage(url: Any?, context: Context) {

    if (url == null || (url is CharSequence && url.isEmpty()) || url is Int && url == View.NO_ID) {
        setImageDrawable(context.getDrawable(R.drawable.icon_csc))
        return
    }

    val requestOptions = RequestOptions()
    requestOptions.placeholder(context.getDrawable(R.drawable.icon_csc))
    requestOptions.fitCenter()

    Glide.with(context).load(url).apply(requestOptions).into(this)
}